package com.excel;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 在表头初始化的过程中，也就决定了列的显示顺序
 * 
 * @author mike
 */
public class TableMergedColumns extends MergedColumns {

    private List<Element> rowList;
    StringMergedColumns stringMergedColumns;
    public TableMergedColumns(String htmlTable) {
	
	//for test
	Document document = null;
	try {
	    document = DocumentHelper.parseText(htmlTable);	   
	} catch (DocumentException e) {		   
	    e.printStackTrace();
	}
	Element element = document.getRootElement();
	this.rowList  = element.elements("tr");		
	Element firstRow = rowList.get(0);
	Element secondRow = rowList.get(1);
	StringBuffer sbf = new StringBuffer();
	List<Element> complexDisplayNames = firstRow.elements("td");
	List<Element> fieldDisplayNames = secondRow.elements("td");
	// 转为字符串格式
	for (int i = 0; i < fieldDisplayNames.size(); i++) {
//	     System.out.println(fieldDisplayNames.get(i).getText());

	}
	int currentFieldIndex = 0;
	for (int i = 0; i < complexDisplayNames.size(); i++) {
	    Element tdElement = complexDisplayNames.get(i);	   
	    String colsSpanStr = tdElement.attributeValue("colspan");
	    int colspan = colsSpanStr == null ? 1 : Integer
		    .parseInt(colsSpanStr);
	    if (colspan > 1) {
		StringBuffer subSbf = new StringBuffer();
		String elementName = complexDisplayNames.get(i).getText();

		sbf.append(";" + elementName + "(");

		String subName = fieldDisplayNames.get(currentFieldIndex + 0)
			.getText();
		subSbf.append(subName + ":" + "");
		for (int j = 1; j < colspan; j++) {
		    subName = fieldDisplayNames.get(currentFieldIndex + j)
			    .getText();
		    subSbf.append("," + subName + ":" + "");

		}
		sbf.append(subSbf);
		sbf.append(")");

	    } else {
		String elementName = fieldDisplayNames.get(i).getText();
		sbf.append(";(" + elementName + ":" + ")");
	    }

	    currentFieldIndex += colspan;
	}	
	String format = sbf.substring(1);
	stringMergedColumns = new StringMergedColumns(format);
	
    }

    /**
     * 通过字符串格式合并列
     * 
     * @param formatNames
     *                格式为：html table格式
     */
    public List<ExcelColumn> mergeColumn() {
	stringMergedColumns.mergeColumn();
	this.allFieldsList = stringMergedColumns.allFieldsList;
	this.list = stringMergedColumns.list;
	return this.list;
    }

}
